<?php


namespace App\Services\Jobposition;

use App\Models\JobpositionStatisticsModel;
use App\Models\JobpositionUvLogModel;
use App\Models\User;
use App\Services\AbstractBaseService;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Support\Facades\DB;

class StatisticsService extends AbstractBaseService
{
    /**
     * 用户浏览时增加访问次数
     * @param int $job_position_id
     * @param string $idfa
     * @param Authenticatable|User|null $user
     * @return void
     */
    public function browse(int $job_position_id, Authenticatable|User|null $user, string $idfa = ''): void
    {
        $updateArray = [];
        $updateArray['pv'] = DB::raw('`pv` + 1');
        if ($idfa) {
            //没有广告id只增加浏览量
            $res = JobpositionUvLogModel::query()->where('job_position_id', $job_position_id)->where('idfa', $idfa)->first();
            if (!$res) {
                JobpositionUvLogModel::query()->create([
                    'job_position_id' => $job_position_id,
                    'idfa' => $idfa,
                    'user_id' => $user->id ?? 0,
                    'num' => 1,
                ]);
                $updateArray['uv'] = DB::raw('`uv` + 1');
            } else {
                $res->update([
                    'num' => DB::raw('`num` + 1'),
                ]);
            }
        }
        if ($updateArray) {
            JobpositionStatisticsModel::query()->updateOrCreate([
                'job_position_id' => $job_position_id,
            ],
                $updateArray
            );
        }
    }
}